package com.supply.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
 * 进行登录认证时的过滤器，用于处理特殊的登录逻辑
 */
public class CustomFromAuthenticationFilter extends FormAuthenticationFilter {
    private final String successUrl="/toLoginSuccess";
    private static final String REQUEST_TYPE = "OPTIONS";

    /**
     * 登录认证成功时执行该方法，自定义跳转路径
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        WebUtils.getAndClearSavedRequest(request);
        WebUtils.redirectToSavedRequest(request, response, successUrl); //重定向跳转路径
        return false;
    }

    /**
     * 登陆认证失败时会进入的方法，测试用
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
//        System.out.println("登录失败了");
        return super.onLoginFailure(token, e, request, response);
    }

    //过滤掉“OPTIONS”请求
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals(REQUEST_TYPE)) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
